package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.domain.Config;
import com.chen.mapper.ConfigMapper;
import com.chen.service.ConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService {

    @Resource
    private ConfigMapper configMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Page<Config> findByPage(Page<Config> page, String type, String name, String code) {
        return page(page, new LambdaQueryWrapper<Config>()
                .like(!StringUtils.isEmpty(type), Config::getType, type)
                .like(!StringUtils.isEmpty(name), Config::getName, name)
                .like(!StringUtils.isEmpty(code), Config::getCode, code)
        );
    }

    @Override
    public Config getConfigByCode(String code) {

        //查询缓存
        List<Config> configList = (List<Config>) redisTemplate.opsForValue().get("CONFIG_SYSTEM");

        Config configX = null;
        for (Config config : configList) {
            if (config.getCode().equals(code)) {
                configX = config;
                break;
            }
        }
        if (configX == null) {
            configX = configMapper.selectByCode(code);
            if (configX != null) {
                redisTemplate.opsForValue().set("CONFIG_SYSTEM", configMapper.selectList(null));
            }
        }

        return configX;
    }
}
